import {
  DBPost
} from '../../../data/db-cloud.js';

Page({
  data: {
    useKeyboardFlag: true,
    showMediaFlag: false,
    choosedImgs: []
  },
 async onLoad(options) {
    const postId = options.id
    console.log(postId)
    this.dbPost = new DBPost(postId)
    const comments = await this.dbPost.getCommentData()
    console.log(comments)
    // 绑定评论数据
    this.setData({
      comments: comments
    });
    this.initRecordMgr()
    this.initAudioMgr()
  },
  switchInputType(event) {
    this.setData({
      useKeyboardFlag: !this.data.useKeyboardFlag
    })
  },
  showMedia() {
    this.setData({
      showMediaFlag: !this.data.showMediaFlag
    })
  },
  afterSelectPics(event) {
    const {
      file
    } = event.detail;
    console.log(file)
    this.setData({
      choosedImgs: this.data.choosedImgs.concat(file)
    })
    // this.data.fileList = file
  },
  previewImg(event) {
    //获取评论序号
    const commentIdx = event.currentTarget.dataset.commentIdx
    //获取图片在图片数组中的序号
    const imgIdx = event.currentTarget.dataset.imgIdx
    //获取评论的全部图片
    const imgs = this.data.comments[commentIdx].content.img;
    wx.previewImage({
      current: imgs[imgIdx], // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  bindCommentInput(event) {
    const val = event.detail.value;
    console.log(val);
    this.data.keyboardInputValue = val;
  },
  // 提交用户评论
  async submitComment(event) {
    console.log(this.data.choosedImgs)
    const imgsTempUrl = this.data.choosedImgs.map(i=>i.tempFilePath)
    const imgCloudIds = await this.dbPost
          .uploadImgsToCloud(imgsTempUrl,'comment-imgs')
    const newData = {
      username: "青石",
      avatar: "/images/avatar/avatar-3.png",
      // 评论时间
      create_time: new Date().getTime() / 1000,
      // 评论内容
      content: {
        txt: this.data.keyboardInputValue,
        img: imgCloudIds
      },
    };
    console.log(newData)
    if (!newData.content.txt) {
      // 如果没有评论内容，就不执行任何操作
      return;
    }
    //保存新评论到缓存数据库中
    await this.dbPost.newComment(newData);
    //显示操作结果
    this.showCommitSuccessToast();
    //重新渲染并绑定所有评论
    this.bindCommentData();
    //恢复初始状态
    this.resetAllDefaultStatus();
  },

  //评论成功
  //@post-comment.js
  showCommitSuccessToast() {
    //显示操作结果
    wx.showToast({
      title: "评论成功",
      duration: 1000,
      icon: "success"
    })
  },
  async bindCommentData() {
    const comments =  await this.dbPost.getCommentData();
    console.log(comments)
    // 绑定评论数据
    this.setData({
      comments: comments
    });
  },
  resetAllDefaultStatus() {
    //清空评论框、清空image-picker并关闭面板
    this.setData({
      keyboardInputValue: '',
      choosedImgs: [],
      showMediaFlag: false
    });
  },

  // 开始录音
  // @post-comment.js
  recordStart() {
    this.setData({
      recodingClass: 'recoding'
    });
    this.rMgr.start()
  },

  //结束录音
  recordEnd() {
    this.setData({
      recodingClass: ''
    });
    this.rMgr.stop()
  },

  // 初始化全局录音管理器对象
  // @post-comment.js
  initRecordMgr() {

    // 初始化录音管理器
    var rMgr = wx.getRecorderManager()
    this.rMgr = rMgr
    rMgr.onStart(() => {
      console.log('start record')
    })

    rMgr.onStop((res) => {
      console.log('stop record', res)
      const {
        tempFilePath,
        duration
      } = res

      //发送录音
      this.submitVoiceComment({
        url: tempFilePath,
        timeLen: Math.ceil(duration / 1000)
      });
    })
  },

  //提交录音
  // @post-comment.js
  async submitVoiceComment(audio) {
      const cloudId = await this.dbPost
        .uploadAudioToCloud(audio.url,'comment-audios')
      audio.url = cloudId
      var newData = {
        username: "青石",
        avatar: "/images/avatar/avatar-3.png",
        create_time: new Date().getTime() / 1000,
        content: {
          txt: '',
          img: [],
          audio: audio
        },
    };

    //保存新评论到缓存数据库中
    await this.dbPost.newComment(newData);

    //显示操作结果
    this.showCommitSuccessToast();

    //重新渲染并绑定所有评论
    this.bindCommentData();
  },

  initAudioMgr() {
    // 初始化录音管理器
    const aMgr = wx.createInnerAudioContext()
    aMgr.autoplay = true
    this.aMgr = aMgr
    this.playing = false

    aMgr.onPlay(() => {
      console.log('start play')
      this.playing = true
    })

    aMgr.onEnded(() => {
      console.log('ended play')
      this.playing = false
    })

    aMgr.onStop((res) => {
      console.log('stop play')
      this.playing = false
    })
  },
  // 新增播放函数
  // @post-comment.js  
  playAudio(event) {
    const url = event.currentTarget.dataset.url
    // 如果正在播放
    if (this.playing) {
      if (url == this.aMgr.src) {
        // 如果url相同说明是结束播放当前音频
        this.aMgr.stop()
      } else {
        // 如果url不同则说明用户点了另外的音频
        // 需要立即播放新音频
        this.aMgr.src = url
      }
    }

    //如果没有播放，那么立即播放
    else {
      this.aMgr.src = url
    }
  }
})